package com.foreknow.demo18;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Jdbc的工具类
 */
public class DBTools {
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    /**
     * 创建连接
     */
    public Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/basic2","root","123456");
        return conn;
    }
    /**
     * 查询
     * @param sql SQL语句
     * @param values 动态可变参数  Object[]
     *
     */
    public ResultSet getQuery(String sql,Object...values) throws SQLException {
        //获取到预处理
        pstmt = conn.prepareStatement(sql);
        //遍历数组
        for(int i = 0;i<values.length;i++) {
            //将？替换成具体的值
            pstmt.setObject(i+1,values[i]);
        }
        rs = pstmt.executeQuery();
        //思考：对结果集是遍历好还是不遍历好呢？不需要遍历
        //如果遍历，以后要通过这个方法再查询别的表就用不了这个方法了
        return rs;
    }

    /**
     * DML操作
     */
    public int Dml(String sql,Object...values) throws SQLException {
        //获取到预处理
        pstmt = conn.prepareStatement(sql);
        //遍历数组
        for(int i = 0;i<values.length;i++) {
            //将？替换成具体的值
            pstmt.setObject(i+1,values[i]);
        }
        int a = pstmt.executeUpdate();
        return a ;
    }


    public static void main(String[] args) {
        DBTools dbTools = new DBTools();
        try {
            //1. 连接数据库
            dbTools.getConnection();
            //2. 查询
            //            ResultSet rs = dbTools.getQuery("select * from emp where empno=?",8888);
            //            while (rs.next()) {
            //                int empno = rs.getInt("empno");
            //                String ename = rs.getString("ename");
            //                String job = rs.getString("job");
            //                System.out.println(empno+"--"+ename+"--"+job);
            //            }
            //3. dml
            //int isRigth = dbTools.Dml("insert into emp(empno,ename,job) values(?,?,?)",7777,"yamaha","music");
            int isDelete = dbTools.Dml("delete from emp where empno=?",7777);
            System.out.println(isDelete);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }





    /**
     * 释放资源
     */
}
